import React from 'react';
import styled from 'styled-components';
import {useTags} from 'hooks/useTags';

const Wrapper = styled.section`
  flex-grow: 1;
  flex-shrink: 1;
  overflow: auto;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  padding: 16px;
  line-height: 24px;
   .newTag {
    > button {
      background: none;
      color: ${props => props.theme.main};
      border: none;
      border-bottom: 1px solid;
      padding: 0 4px;
      margin-top: 8px;
    }
  }
  > ol {
  margin-top: 20px;
    flex-shrink: 1;
    > li {
      background-color: #d9d9d9;
      display: inline-block;
      border-radius: 20px;
      padding: 2px 20px;
      margin-right: 12px;
      margin-bottom: 12px;
      font-size: 14px;

      &.selected {
        background-color: ${props => props.theme.main};
        color: white;
      }
    }
  }


`;
type Props = {
  value: number[],
  onChange: (selected: number[]) => void,
}
const TagsSection: React.FC<Props> = (props) => {
    const {tags, addTag} = useTags();
    const selectedTagIds = props.value;

    const onToggleTag = (tagId: number) => {
      const index = selectedTagIds.indexOf(tagId);
      if (index >= 0) {
        props.onChange(selectedTagIds.filter(t => t !== tagId));
        // 如果已经tag已被选中，就复制所有没有被选中的tag,作为新的selectedTags
      } else {
        props.onChange([...selectedTagIds, tagId]);
      }
    };
    const getClass = (tagId: number) => selectedTagIds.indexOf(tagId) >= 0 ? 'selected' : '';
    return (
      <Wrapper>
        <div className='newTag'>
          <button onClick={addTag}>新增标签</button>
        </div>
        <ol>
          {tags.map(tag =>
            <li key={tag.id} onClick={() => onToggleTag(tag.id)}
                className={getClass(tag.id)}>{tag.name}</li>
          )}
        </ol>

      </Wrapper>
    );
  }
;

export {TagsSection};
